//
//  MMFCMManager.m
//  mmosite
//
//  Created by aron on 2017/4/18.
//  Copyright © 2017年 qingot. All rights reserved.
//

#import "MMFCMManager.h"
#import <YYModel/YYModel.h>

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@import UserNotifications;
#endif

@import Firebase;

NSString *const kGCMMessageIDKey = @"gcm.message_id";
NSString *const kMMFCMMessageTitleKey = @"ti";
NSString *const kMMFCMMessageUrlKey = @"ur";
NSString *const kMMFCMMessageIDKey = @"id";
NSString *const kMMFCMMessageTypeKey = @"ty";


#pragma mark - ......::::::: MMNotificationModel :::::::......

typedef NS_ENUM(NSUInteger, MMNotificationType) {
    MMNotificationTypeNews = 1,
};

@interface MMNotificationModel : NSObject<YYModel>

@property (nonatomic, assign) MMNotificationType type;
@property (nonatomic, copy) NSString* title;
@property (nonatomic, copy) NSString* _id;
@property (nonatomic, copy) NSString* url;

@end

@implementation MMNotificationModel

+ (NSDictionary *)modelCustomPropertyMapper {
    return @{@"type"  : @"ty",
             @"title"  : @"ti",
             @"_id"  : @"id",
             @"url": @"ur"};
}

@end


#pragma mark - ......::::::: MMFCMManager :::::::......

@interface MMFCMManager ()<UNUserNotificationCenterDelegate, FIRMessagingDelegate>

@end

@implementation MMFCMManager

DEF_SINGLETON

- (void)setupNotificationConfigWithApplication:(UIApplication *)application {

    // iOS 8 or later
    // [START register_for_notifications]
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
        UIUserNotificationType allNotificationTypes =
        (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings =
        [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        // iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
        // For iOS 10 display notification (sent via APNS)
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
        UNAuthorizationOptions authOptions =
        UNAuthorizationOptionAlert
        | UNAuthorizationOptionSound
        | UNAuthorizationOptionBadge;
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
        }];
        
        [FIRMessaging messaging].remoteMessageDelegate = self;
#endif
    }
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
    [FIRApp configure];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:)
                                                 name:kFIRInstanceIDTokenRefreshNotification object:nil];
}

// [START refresh_token]
- (void)tokenRefreshNotification:(NSNotification *)notification {
    // Note that this callback will be fired everytime a new token is generated, including the first
    // time. So if you need to retrieve the token as soon as it is available this is where that
    // should be done.
    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    NSLog(@"InstanceID token: %@", refreshedToken);
    
    // Connect to FCM since connection may have failed when attempted before having a token.
    [self connectToFcm];
    
    // TODO: If necessary send token to application server.
}


// [START connect_to_fcm]
- (void)connectToFcm {
    // Won't connect since there is no token
    if (![[FIRInstanceID instanceID] token]) {
        return;
    }
    
    // Disconnect previous FCM connection if it exists.
    [[FIRMessaging messaging] disconnect];
    
    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Unable to connect to FCM. %@", error);
        } else {
            NSLog(@"Connected to FCM.");
        }
    }];
}
// [END connect_to_fcm]

- (void)disconnect {
    [[FIRMessaging messaging] disconnect];
}


// [START ios_10_data_message_handling]
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Receive data message on iOS 10 devices while app is in the foreground.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
    // Print full message
    NSLog(@"%@", remoteMessage.appData);
}
#endif
// [END ios_10_data_message_handling]


/**
 处理通知
 @param userInfo 通知信息
 */
- (void)handleNotification:(NSDictionary *)userInfo {
    if (userInfo[kGCMMessageIDKey]) {
        BMLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }
    
    // 处理消息
    MMNotificationModel* notificationModel = [MMNotificationModel yy_modelWithDictionary:userInfo];
    if (notificationModel.type == MMNotificationTypeNews) {
        BMLog(@"applicationState = %@", @([UIApplication sharedApplication].applicationState));
        if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
            // 新闻消息
            // TODO: zyt 处理消息
        }
    }
    
}


@end
